//
//  LYLSearchViewController.m
//  ONE
//
//  Created by dllo on 16/6/7.
//  Copyright © 2016年 GroupNine. All rights reserved.
//

#import "LYLSearchViewController.h"
#import "DZNSegmentedControl.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>
#import "LFBNetTool.h"
#import "LYLHomeItemModel.h"
#import "LYLReadItemModel.h"
#import "LYLMusicItemModel.h"
#import "LYLMovieItemModel.h"
#import "LYLAuthorItemModel.h"
#import "LYLSearchPictureCell.h"
#import "LYLSearchReadCell.h"
#import "LYLSearchMusicCell.h"
#import "LYLSearchMovieCell.h"
#import "LYLSearchAuthorCell.h"

@interface LYLSearchViewController () <UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate, DZNEmptyDataSetSource>
/** 搜索栏 */
@property (strong, nonatomic) UISearchBar *searchBar;
@property (strong, nonatomic) UIImageView *hintView;
/** 搜索的五个分栏 */
@property (strong, nonatomic) DZNSegmentedControl *segmentedControl;
/** 搜索结果根视图 */
@property (strong, nonatomic) UITableView *tableView;
/** 加载动画 */
@property (strong, nonatomic) UIActivityIndicatorView *activityIndicatorView;

@end

@implementation LYLSearchViewController
{
    LYLSearchType searchType;
    NSMutableDictionary *dataSource;
}

#pragma mark - Lifecycle

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - View Lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.edgesForExtendedLayout = UIRectEdgeAll;
    self.view.backgroundColor = [UIColor whiteColor];
    //初始结果页面:
    [self initDatas];
    //创建搜索页面视图:
    [self setupViews];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [_searchBar becomeFirstResponder];
}


- (void)initDatas {
    dataSource = [NSMutableDictionary dictionaryWithCapacity:5];
    searchType = LYLSearchTypeHome;
}

#pragma mark -- 设置搜索页面视图:
- (void)setupViews {
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancel)];
    
    _searchBar = [[UISearchBar alloc] init];
    _searchBar.placeholder = @"输入搜索内容";
    _searchBar.tintColor = LYLLightGrayTextColor;
    _searchBar.returnKeyType = UIReturnKeySearch;
    _searchBar.searchBarStyle = UISearchBarStyleMinimal;
    _searchBar.delegate = self;
    self.navigationItem.titleView = _searchBar;
    
    _segmentedControl = [[DZNSegmentedControl alloc] initWithItems:@[@"插图", @"阅读", @"音乐", @"影视", @"作者/音乐人"]];
    _segmentedControl.backgroundColor = [UIColor whiteColor];
    _segmentedControl.frame = CGRectMake(0, 0, SCREEN_WIDTH, 35);
    _segmentedControl.showsCount = NO;
    _segmentedControl.font = FontWithSize(12);
    [_segmentedControl setTitleColor:[UIColor colorWithWhite:127 / 255.0 alpha:1] forState:UIControlStateNormal];
    _segmentedControl.tintColor = LYLAppThemeColor;
    _segmentedControl.hairlineColor = nil;
    [_segmentedControl addTarget:self action:@selector(selectedSegment:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_segmentedControl];
    [_segmentedControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@35);
        make.left.top.right.equalTo(self.view).insets(UIEdgeInsetsMake(64, 0, 0, 0));
    }];
    _segmentedControl.hidden = YES;
    
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView registerClass:[LYLSearchPictureCell class] forCellReuseIdentifier:@"picCell"];
    [_tableView registerClass:[LYLSearchReadCell class] forCellReuseIdentifier:@"readCell"];
    [_tableView registerClass:[LYLSearchMusicCell class] forCellReuseIdentifier:@"musicCell"];
    [_tableView registerClass:[LYLSearchMovieCell class] forCellReuseIdentifier:@"movieCell"];
    [_tableView registerClass:[LYLSearchAuthorCell class] forCellReuseIdentifier:@"authorCell"];
    _tableView.tableFooterView = [UIView new];
    _tableView.emptyDataSetSource = self;
    [self.view addSubview:_tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_segmentedControl.bottom);
        make.left.bottom.right.equalTo(self.view);
    }];
    _tableView.hidden = YES;
    
    _hintView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search_all"]];
    self.hintView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_hintView];
    [_hintView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.sizeOffset(CGSizeMake(165, 110));
        make.top.equalTo(self.view).offset(120);
        make.centerX.equalTo(self.view);
    }];
    
    _activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _activityIndicatorView.hidesWhenStopped = YES;
    [self.view addSubview:_activityIndicatorView];
    [_activityIndicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
    }];
}

#pragma mark -- 从数据源数组中取出当前搜索类型的数组的方法:
- (NSArray *)dataByCurrentSearchType {
    NSArray *datas = dataSource[[@(searchType) stringValue]];
    return datas;
}

#pragma mark - 点击取消按钮方法:
- (void)cancel {
    [_searchBar resignFirstResponder];
    [self dismissViewControllerAnimated:YES completion:NULL];
}

#pragma mark -- 点击分段控件分栏方法:
- (void)selectedSegment:(DZNSegmentedControl *)seg {
    switch (seg.selectedSegmentIndex) {
        case 0:
            searchType = LYLSearchTypeHome;
            break;
        case 1:
            searchType = LYLSearchTypeRead;
            break;
        case 2:
            searchType = LYLSearchTypeMusic;
            break;
        case 3:
            searchType = LYLSearchTypeMovie;
            break;
        case 4:
            searchType = LYLSearchTypeAuthor;
            break;
    }
    [self searching];
}

#pragma mark -- 获取拼接的类型:
- (NSString *)apiStringForSearchWithSearchType:(LYLSearchType)type {
    switch (type) {
        case LYLSearchTypeHome:
            return LYLApiHomePage;
        case LYLSearchTypeRead:
            return LYLApiReading;
        case LYLSearchTypeMusic:
            return LYLApiMusic;
        case LYLSearchTypeMovie:
            return LYLApiMovie;
        case LYLSearchTypeAuthor:
            return LYLApiAuthor;
        default:
            return @"";
    }
}

#pragma mark - 开始搜索:
- (void)searching {
    [_activityIndicatorView startAnimating];
    [LFBNetTool getNetWithURL:[NSString stringWithFormat:LYLApiSearching, [self apiStringForSearchWithSearchType:searchType], _searchBar.text] Body:nil Header:nil Response:LFBJSON Success:^(id result) {
        if ([result[@"res"] integerValue] == 0) {
        NSMutableArray *results = [NSMutableArray array];
            NSArray *data = result[@"data"];
            switch (searchType) {
                case LYLSearchTypeHome: {
                    for (NSDictionary *dic in data) {
                        LYLHomeItemModel *model = [[LYLHomeItemModel alloc] initWithDic:dic];
                        [results addObject:model];
                    }
                    break;
                }
                case LYLSearchTypeRead: {
                    for (NSDictionary *dic in data) {
                        LYLReadItemModel *model = [[LYLReadItemModel alloc] initWithDic:dic];
                        [results addObject:model];
                    }
                    break;
                }
                case LYLSearchTypeMusic: {
                    for (NSDictionary *dic in data) {
                        LYLMusicItemModel *model = [[LYLMusicItemModel alloc] initWithDic:dic];
                        [results addObject:model];
                    }
                    break;
                }
                case LYLSearchTypeMovie: {
                    for (NSDictionary *dic in data) {
                        LYLMovieItemModel *model = [[LYLMovieItemModel alloc] initWithDic:dic];
                        [results addObject:model];
                    }
                    break;
                }
                case LYLSearchTypeAuthor: {
                    for (NSDictionary *dic in data) {
                        LYLAuthorItemModel *model = [[LYLAuthorItemModel alloc] initWithDic:dic];
                        [results addObject:model];
                    }
                    break;
                }
            }
        
            if (results) {
                [dataSource setObject:results forKey:[@(searchType) stringValue]];
                _segmentedControl.hidden = NO;
                _tableView.hidden = NO;
                _hintView.hidden = YES;
                
                [_tableView reloadData];
            }
            else
            {
                _hintView.hidden = NO;
            }
            [_activityIndicatorView stopAnimating];
        }
    } Failure:^(NSError *error) {
//        [self showHUDServerError];
        NSLog(@"%@", error);
    }];
}

#pragma mark - UISearchBarDelegate(点击搜索按钮)
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [_searchBar resignFirstResponder];
    [self searching];
}

#pragma mark - DZNEmptyDataSetSource(没有搜索结果视图)
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"search_null_image"];
}

#pragma mark -- cell行数:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self dataByCurrentSearchType].count;
}

#pragma mark -- cell内容:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (searchType) {
        case LYLSearchTypeHome:
            return [tableView dequeueReusableCellWithIdentifier:@"picCell" forIndexPath:indexPath];
        case LYLSearchTypeRead:
            return [tableView dequeueReusableCellWithIdentifier:@"readCell" forIndexPath:indexPath];
        case LYLSearchTypeMusic:
            return [tableView dequeueReusableCellWithIdentifier:@"musicCell" forIndexPath:indexPath];
        case LYLSearchTypeMovie:
            return [tableView dequeueReusableCellWithIdentifier:@"movieCell" forIndexPath:indexPath];
        case LYLSearchTypeAuthor:
            return [tableView dequeueReusableCellWithIdentifier:@"authorCell" forIndexPath:indexPath];
    }
    
    return nil;
}

#pragma mark -- cell高度:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (searchType) {
        case LYLSearchTypeHome:
            return [LYLSearchPictureCell cellHeight];
        case LYLSearchTypeRead:
            return [LYLSearchReadCell cellHeight];
        case LYLSearchTypeMusic:
            return [LYLSearchMusicCell cellHeight];
        case LYLSearchTypeMovie:
            return [LYLSearchMovieCell cellHeight];
        case LYLSearchTypeAuthor:
            return [LYLSearchAuthorCell cellHeight];
    }
    return 0;
}

#pragma mark -- cell将要显示给cell赋值:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
//    MLBBaseModel *model = [self dataByCurrentSearchType][indexPath.row];
    switch (searchType) {
        case LYLSearchTypeHome:
            [(LYLSearchPictureCell *)cell setModel:[self dataByCurrentSearchType][indexPath.row]];
            break;
        case LYLSearchTypeRead:
            [(LYLSearchReadCell *)cell setModel:[self dataByCurrentSearchType][indexPath.row]];
            break;
        case LYLSearchTypeMusic:
            [(LYLSearchMusicCell *)cell setModel:[self dataByCurrentSearchType][indexPath.row]];
            break;
        case LYLSearchTypeMovie:
            ((LYLSearchMovieCell *)cell).titleLabel.text = ((LYLMovieItemModel *)[self dataByCurrentSearchType][indexPath.row]).title;
            break;
        case LYLSearchTypeAuthor:
            [(LYLSearchPictureCell *)cell setModel:[self dataByCurrentSearchType][indexPath.row]];
            break;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    switch (searchType) {
        case LYLSearchTypeHome: {
//            MLBSingleHomeViewController *singleHomeViewController = [[MLBSingleHomeViewController alloc] init];
//            singleHomeViewController.homeItem = [self dataByCurrentSearchType][indexPath.row];
//            [self.navigationController pushViewController:singleHomeViewController animated:YES];
            break;
        }
        case LYLSearchTypeRead: {
            break;
        }
        case LYLSearchTypeMusic: {
//            MLBMusicRelatedViewController *musicRelatedViewController = [[MLBMusicRelatedViewController alloc] init];
//            musicRelatedViewController.relatedMusic = [self dataByCurrentSearchType][indexPath.row];
//            [self.navigationController pushViewController:musicRelatedViewController animated:YES];
            break;
        }
        case LYLSearchTypeMovie: {
//            MLBMovieDetailsViewController *movieDetailsViewController = [[MLBMovieDetailsViewController alloc] init];
//            movieDetailsViewController.movieListItem = [self dataByCurrentSearchType][indexPath.row];
//            [self.navigationController pushViewController:movieDetailsViewController animated:YES];
            break;
        }
        case LYLSearchTypeAuthor: {
            
            break;
        }
    }
}


@end
